package com.shpng.cheapenglish.manager;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;

import com.shpng.cheapenglish.db.User;
import com.shpng.cheapenglish.entity.SUser;
import com.shpng.cheapenglish.persistent.PMF;
import com.shpng.cheapenglish.persistent.UserPersistent;
import com.shpng.cheapenglish.util.StringUtils;

public class UserManager {

	private static UserManager userManager;

	private UserPersistent userPersistent;

	private List<SUser> users = new ArrayList<SUser>();

	private UserManager() {
		userPersistent = UserPersistent.getInstance();
		initUser();
	}

	public static UserManager getInstance() {
		if (userManager == null)
			userManager = new UserManager();
		return userManager;
	}

	public boolean addUser(String email) {
		SUser su = getUser(email);
		if (su == null) {
			User user = new User();
			user.setEmail(email);
			saveOrUpdateUser(user);
			su = new SUser(user);
			users.add(su);
			return true;
		}
		return false;
	}

	public void saveOrUpdateUser(User user) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		userPersistent.saveUser(user, pm);
		pm.close();
	}

	public SUser getUser(String email) {
		if (StringUtils.isEmpty(email))
			return null;
		for (SUser user : users) {
			if (email.equals(user.getEmail())) {
				return user;
			}
		}
		return null;
	}

	public List<SUser> getUsers() {
		return users;
	}

	public void initUser() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		List<User> dbUsers = userPersistent.getUsers(pm);
		for (User u : dbUsers) {
			SUser user = new SUser(u);
			users.add(user);
		}
	}

	public SUser getUser(long userId) {
		if (userId < 0)
			return null;
		for (SUser user : users) {
			if (userId == user.getId()) {
				return user;
			}
		}
		return null;
	}

}
